package com.google.code.mamule.integration;

import com.google.code.mamule.config.MamuleSecurity;
import com.google.code.mamule.user.ActiveUser;
import com.google.code.mamule.user.User;
import com.google.code.mamule.user.UserRepository;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;

/**
 * Created with IntelliJ IDEA. User: borck_000 ; Date: 12/22/13 ; Time: 10:32 PM
 */
@Component
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.INTERFACES)
public class SecurityContextActiveUser implements ActiveUser {

  private static final Logger log = LoggerFactory.getLogger(SecurityContextActiveUser.class);

  private UserRepository users;

  @Autowired
  public SecurityContextActiveUser(final UserRepository users) {
    this.users = users;
  }

  @Override
  public User get() {
    Authentication auth = fetchAuth();
    UserDetails details = (UserDetails) auth.getPrincipal();
    User active = users.findOne(details.getUsername());
    assert active != null : "logged in user not registered";
    return active;
  }

  private Authentication fetchAuth() {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth == null) {
      // die
      throw new AssertionError("FATAL >> requiring active user in non-restricted area");
    }
    log.debug("logged in user's details : ", auth.getPrincipal());
    return auth;
  }

  @Override
  public boolean isAdmin() {
    final Authentication auth = fetchAuth();
    return auth.getAuthorities().contains(MamuleSecurity.ROLE_ADMIN);
  }
}
